<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Admin extends BaseController {
    private $powerTimeName = 'brand_power_time';
    private $brandPawName = 'brand_paw';
    private $mutiCampusName = 'muti_campus';
    // 定时开关机v2
    private $powerTimeV2Name = 'brand_power_time_v2';

	public function __construct() {
        parent::__construct();
        // 后台初始化方法
        $this->admin_init();
        // 如果是超管，就跳转到超管的控制器
        if($this->userType != USER_TYPE_SUPER_ADMIN) redirect(admin_url("login"));
        // 加载库
        $this->load->model('schoolModel');
        $this->load->model('accountModel');
        $this->load->model('classesModel');
        $this->load->model('dataModel');
        $this->load->model('sourceModel');
        $this->load->model('configModel');
    }

    // 后台首页
	public function index() {
        //获取首页统计信息
        $indexData = $this->_get_index_data();
        // $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "admin". DIRECTORY_SEPARATOR. "index");
        $this->displayWithData(ADMIN_DIR. DIRECTORY_SEPARATOR. "admin". DIRECTORY_SEPARATOR. "index", $indexData);
	}
    // 菜单管理
    public function menu(){
        // 全部权限菜单
        $menuList = $this->accountModel->get_admin_menu_all();
        // 管理员菜单
        $adminMenu = $userMenu = array();
        foreach($menuList as $menu) {
            $menuId = $menu['id'];
            $menuPid = $menu['menu_pid'];
            $menuRole = $menu['menu_role_type'];
            $menuRoleArray = explode(",", $menuRole);

            // 初始化数据
            $menuEditAction = '<a href="javascript:;" class="menu-edit green"><i class="fa fa-pencil bigger-120"></i> 修改</a>';
            $menuDeleteAction = '<a href="javascript:;" class="menu-delete red"><i class="fa fa-trash-o bigger-120"></i> 删除</a>';
            $menuAddSubAction = $menuPid == 0 ? '<a href="javascript:;" class="menu-add-sub blue"><i class="fa fa-plus bigger-120"></i> 添加子菜单</a>' : '';
            $menuIcon = $menu['menu_icon'] ? '<i class="menu-icon fa fa-'. $menu['menu_icon'] .'"></i> ' : '';
            $menuName = '<span>'. $menu['menu_name'] .'</span>';
            $tree['text'] = $menuIcon. $menuName. $menuDeleteAction. $menuEditAction. $menuAddSubAction;
            $tree['type'] = $menuPid ? 'item' : 'folder';
            $tree['attr'] = array("id" => $menuId);

            // 父级菜单
            if($menuPid == 0) {
                $menu['additionalParameters']['children'] = array();
                if(in_array(USER_TYPE_SUPER_ADMIN, $menuRoleArray)) $adminMenu["label_". $menuId] = $tree;
                if(in_array(USER_TYPE_SCHOOL, $menuRoleArray)) $userMenu["label_". $menuId] = $tree;
            } else {
                // 子菜单
                if(in_array(USER_TYPE_SUPER_ADMIN, $menuRoleArray)) $adminMenu["label_". $menuPid]['additionalParameters']['children'][] = $tree;
                if(in_array(USER_TYPE_SCHOOL, $menuRoleArray)) $userMenu["label_". $menuPid]['additionalParameters']['children'][] = $tree;
            }
        }
        // 菜单
        $this->adminMenu = json_encode($adminMenu);
        $this->userMenu = json_encode($userMenu);
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "admin". DIRECTORY_SEPARATOR. "menu");
    }
    // 菜单提交
    public function menu_submit_action(){
        $menuId = $this->post("id");
        $menuPid = $this->post("menu_pid");
        $menuName = $this->post("menu_name");
        $menuRole = $this->post("menu_role_type");
        $menuUrl = $this->post("menu_url");
        $menuIcon = $this->post("menu_icon");
        $menuSort = $this->post("menu_sort");
        // 内容检查
        if(!$menuName) throw new Exception("请填写菜单名称");
        if(!$menuRole) throw new Exception("请选择所属权限");

        // 入库
        $data['menu_name'] = $menuName;
        $data['menu_desc'] = $this->post("menu_desc");
        $data['menu_pid'] = $menuPid;
        $data['menu_role_type'] = $menuRole;
        $data['menu_url'] = $menuUrl;
        $data['menu_icon'] = $menuIcon;
        $data['menu_sort'] = $menuSort;
        $data['updatetime'] = date("Y-m-d H:i:s");
        if($menuId) {
            $this->db->update(AccountModel::$menuTable, $data,"id='{$menuId}'");
        } else {
            $data['createtime'] = $data['updatetime'];
            $this->db->insert(AccountModel::$menuTable, $data);
        }
        exit(json("保存菜单成功", true));
    }
    // 删除菜单
    public function menu_delete_action(){
        $menuId = $this->post("id");
        // 获取子菜单列表
        $subMenu = $this->accountModel->get_sub_menu_by_id($menuId);
        if($subMenu) throw new Exception("当前菜单存在二级菜单，删除失败");

        // 删除菜单
        $this->db->delete(AccountModel::$menuTable, array("id"=> $menuId));
        exit(json("删除菜单成功", true));
    }
    // 获取菜单信息
    public function get_menu_info(){
        $menuId = $this->get("id");
        $menuInfo = $this->accountModel->get_menu_info($menuId);
        if(!$menuInfo) throw new Exception("菜单不存在，修改失败");
        
        // 获取上级菜单名
        $parentMenu = $this->accountModel->get_menu_info($menuInfo['menu_pid']);
        $menuInfo['parentName'] = $parentMenu['menu_name'] ? $parentMenu['menu_name'] : '一级菜单';

        exit(json("", true, $menuInfo));
    }

    // 学校管理
    public function school(){
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "admin". DIRECTORY_SEPARATOR. "school");
    }
    // 获取学校列表
    public function get_school_list(){
        // 获取权限菜单列表
        // 获取功能模块
        $params['userType'] = USER_TYPE_SCHOOL;
        $params['parentId'] = 0;
        $menuList = $this->accountModel->get_admin_menu_all($params);
        $menuList = array_value_to_key($menuList, "id");


        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        // 过滤软删除
        $totalParams['isDelete'] = 0;
        $total = $this->schoolModel->get_school_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['field'] = 'id, `school_name` AS `schoolName`, `school_from`, `school_module_set`, `school_face_detect`, `school_brand_update`, `createtime`, `school_exam`, `brand_theme`, `expire_date` ';
        // 过滤软删除
        $data['isDelete'] = 0;
        $schoolList = $this->schoolModel->get_school_list($data);
        foreach($schoolList as &$school) {
            // 功能模块
            $moduleArray = array();
            $moduleSet = explode(",", $school['school_module_set']);
            foreach($moduleSet as $moduleId) {
                if(isset($menuList[$moduleId])) $moduleArray[] = $menuList[$moduleId]['menu_name'];
            }
            $school['module'] = $moduleArray;
            // 获取班牌主题颜色style
            $school['themeStyle'] = get_brand_theme_style($school['brand_theme']);
            // 获取人脸识别主题颜色style
            if($school['school_face_detect'] == FACE_DETECT_CLOSE) {
                $school['faceStyle'] = '<span class="label label-danger ml10">关闭</span>';
            } elseif($school['school_face_detect'] == FACE_DETECT_OPEN) {
                $school['faceStyle'] = '<span class="label label-success ml10">人脸识别</span>';
            } elseif($school['school_face_detect'] == FACE_DETECT_TEMPERATURE) {
                $school['faceStyle'] = '<span class="label label-primary ml10">热成像测温</span>';
            } elseif($school['school_face_detect'] == FACE_DETECT_TEMPERATURE_HEAD) {
                $school['faceStyle'] = '<span class="label label-primary ml10">额温枪测温</span>';
            } else {
                $school['faceStyle'] = '<span class="label label-primary ml10">腕温测温</span>';
            }
        }
        // echo '<pre>';var_export($schoolList);exit;
        // 返回值
        exit(admin_table_data($total, $schoolList));
    }

    // 保存学校登录账号
    public function save_school_account_action(){
        // 账号密码
        $schoolId = $this->post("id");
        $username = $this->post("username");
        $password = $this->post("password");

        // 检查学校是否存在
        $schoolInfo = $this->schoolModel->get_school_info($schoolId);
        if(!$schoolInfo) throw new Exception("学校不存在，请刷新后重试");

        // 检查账号密码格式
        if(!str_is_username($username)) throw new Exception("请填写正确的账号格式");
        if(!str_is_password($password)) throw new Exception("请填写正确的密码格式");
        // 检查账号密码是否存在
        $adminInfo = $this->accountModel->check_username_exists($schoolId, $username, 0, USER_TYPE_SCHOOL);
        if($adminInfo) throw new Exception("账号已存在，请重新输入");
        // 入库
        $insert['school_id'] = $schoolId;
        $insert['username'] = $username;
        $insert['realname'] = $username;
        $insert['password'] = password_hash($password, PASSWORD_DEFAULT);
        $insert['user_type'] = USER_TYPE_SCHOOL;
        $insert['createtime'] = $insert['updatetime'] = date("Y-m-d H:i:s");
        $this->db->insert(AccountModel::$schoolUserTable, $insert);

        exit(json("新增账号成功", true));
    }

    // 获取登录账号
    public function get_school_user_action(){
        $schoolId = $this->get("id");
        $schoolInfo = $this->schoolModel->get_school_info($schoolId);

        $userList = $this->accountModel->get_school_account($schoolId);
        exit(json("", true, $userList));
    }

    // 重置登录密码
    public function reset_school_user_password(){
        $userId = $this->get("id");
        // 修改密码
        $save['password'] = password_hash(123456, PASSWORD_DEFAULT);
        $this->db->update(AccountModel::$schoolUserTable, $save,"id='{$userId}'");

        exit(json("重置登录密码成功", true));
    }
    // 删除用户
    public function delete_school_user(){
        $userId = $this->get("id");
        // 删除用户
        $save['is_delete'] = 1;
        $this->db->update(AccountModel::$schoolUserTable, $save, "id='{$userId}'");
        exit(json("删除账号成功", true));
    }   

    // 学校编辑
    public function school_edit($schoolId = 0) {
        // 获取学校信息
        $this->schoolId = $schoolId;
        $this->schoolInfo = $schoolInfo = $this->schoolModel->get_school_info($schoolId);
        // 获取来源
        $this->schoolFrom = $schoolInfo ? $schoolInfo['school_from'] : $this->get("from");

        // 银通学校
        if($this->schoolFrom == X_DATA_YINTONG) {
            // 是否分校区
            $mutiCampusArr = $this->configModel->get_school_config($schoolId, $this->mutiCampusName);
            if($mutiCampusArr) {
                $this->mutiCampus = $mutiCampusArr['config_value'];
            } else {
                $this->mutiCampus = 0;   
            }
        }

        // 获取省级行政区
        $areaParams['parentId'] = -1;
        $this->province = $this->schoolModel->get_area_list($areaParams);
        // 获取功能模块
        $params['userType'] = USER_TYPE_SCHOOL;
        $params['parentId'] = 0;
        $this->menuList = $this->accountModel->get_admin_menu_all($params);
        // 获取班牌所有主题
        $this->themes = get_all_brand_themes();
        // 获取人脸识别模块列表
        $this->faceList = get_all_face_detect();

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "admin". DIRECTORY_SEPARATOR. "school_edit");
    }
    // 保存学校信息
    public function save_school_action(){
        $schoolId = $this->post("id");
        $schoolFrom = $this->post("school_from");
        // 外部数据参数
        $xDataId = trim($this->post("school_x_id"));
        $xDataParams = $this->post("school_x_params") ? $this->post("school_x_params") : '';
        $xDataToken = $this->post("school_x_token") ? $this->post("school_x_token") : '';
        // 自填数据
        $schoolName = $this->post("school_name");
        $provinceCode = $this->post('school_province');
        $cityCode = $this->post('school_city');
        $areaCode = $this->post('school_area') ? $this->post('school_area') : '';
        $brandTheme = $this->post('brand_theme');
        // 开关
        $schoolFaceDetect = $this->post("school_face_detect") ? $this->post("school_face_detect") : 0;
        $schoolFaceDetectType = $this->post("school_face_detect_type") ? $this->post("school_face_detect_type") : 0;
        $schoolBrandUpdate = $this->post("school_brand_update") ? $this->post("school_brand_update") : 0;
        // $schoolExamQuery = $this->post("school_exam_query") ? $this->post("school_exam_query") : 0;
        $schoolExam = $this->post("school_exam") ? $this->post("school_exam") : 0;
        $schoolSmartLock = $this->post("school_smart_lock") ? $this->post("school_smart_lock") : 0;
        // 虹软SDK版本
        $isFreeFaceSdk = $this->post("face_sdk") == 1 ? 0 : 1;
        // 教师考勤
        $enableTeacherSign = $this->post("enable_teacher_sign") ? $this->post("enable_teacher_sign") : 0;

        $expireDate = $this->post("expire_date") ? $this->post("expire_date") : '';
        $faceSimilar = $this->post("face_similar") ? $this->post("face_similar") : 0.9;
        $notifyExpireTime = $this->post("notify_expire_time") ? $this->post("notify_expire_time") : '';
        if($notifyExpireTime == '0:00') {
            $notifyExpireTime = '';
        }
        if($faceSimilar >= 1 || $faceSimilar < 0.1) {
            throw new Exception('人脸相似度设置不合理');
        }

        if(empty($this->post("school_module_set"))) {
            throw new Exception('功能模块不能为空');
        }
        // // 校训
        // $motto = trim($this->post('school_motto'));
        // 数据检查
        if($schoolFrom == X_DATA_HAOZHUANYE) {
            if(!$xDataId) throw new Exception("请填写学校ID");
            if(!$xDataParams) throw new Exception("请填写接口login参数");
            if(!$xDataToken) throw new Exception("请填写接口token参数");

            // 检查学校ID是否重复
            $hzySchool = $this->schoolModel->check_hzy_schoolid_exists($xDataId, $schoolId);
            if($hzySchool) throw new Exception("学校ID已存在，录入失败");

            // 请求接口
            // $this->load->library("haozhuanyeV2");
            // $result = $this->haozhuanyev2->get_school_info($xDataId);
            // $this->load->library("haozhuanye");
            // $result = $this->haozhuanye->get_school_info($xDataId, $xDataParams, $xDataToken);
            // throw new Exception('aaaaa');

            $this->load->library("haozhuanyeV2");
            $result = $this->haozhuanyev2->get_school_info_by_login_and_token($xDataId, $xDataParams, $xDataToken);   
            // 请求接口出现错误
            if(!isset($result['status'])) {
                throw new Exception('请求接口出现错误');
            }
            if($result['status'] != 'success') throw new Exception($result['errorMessage']);
            $schoolName = $result['result']['schoolInfo']['schoolName'];
            // 添加入库数据
            $data['school_from'] = $schoolFrom;
            $data['school_x_id'] = $xDataId;
            $data['school_x_token'] = $xDataToken;
            $data['school_x_params'] = $xDataParams;
        } elseif($schoolFrom == X_DATA_YINTONG) {
            // 导入银通学校
            if(!$xDataId) throw new Exception("请填写银通接口第三方应用id");
            if(!$xDataParams) throw new Exception("请填写银通接口法人编码");
            if(!$xDataToken) throw new Exception("请填写银通接口秘钥");
            // 检查银通学校ID是否重复
            $ytSchool = $this->schoolModel->check_yt_schoolid_exists($xDataId, $schoolId);
            if($ytSchool) throw new Exception("银通第三方应用id已存在，录入失败");
            // 请求银通接口
            include_once(APPPATH. "libraries/YinTong.php");
            $yintong = new YinTong($xDataId, $xDataParams, $xDataToken);
            $result = $yintong->get_dept_list();
            // var_export($result);exit;

            // 请求银通接口出现错误
            if($result == false || $result['code'] !== '0000') {
                throw new Exception('请求银通接口出现错误');
            }

            // 添加入库数据
            $data['school_from'] = $schoolFrom;
            $data['school_x_id'] = $xDataId;
            $data['school_x_token'] = $xDataToken;
            $data['school_x_params'] = $xDataParams;
        } elseif($schoolFrom == X_DATA_CHAOXING) {
            // 导入超星学校
            if(!$xDataId) throw new Exception("请填写超星学校id");
            // 检查超星学校ID是否重复
            $ytSchool = $this->schoolModel->check_chaoxing_schoolid_exists($xDataId, $schoolId);
            if($ytSchool) throw new Exception("超星学校id已存在，录入失败");
            // 请求超星接口
            include_once(APPPATH. "libraries/Chaoxing.php");
            $chaoxing = new Chaoxing($xDataId, $xDataParams, $xDataToken);
            $schoolInfo = $chaoxing->get_school_info($xDataId);

            if(empty($schoolInfo)) {
                throw new Exception('超星学校id不存在，请重新输入');
            }
            // echo '<pre>';var_export($schoolInfo);exit;
            // 添加入库数据
            $schoolName = $schoolInfo['schoolName'];
            $data['school_from'] = $schoolFrom;
            $data['school_x_id'] = $xDataId;
        } elseif($schoolFrom == X_DATA_FEICHEN) {
            if(!$xDataId) throw new Exception("请填写斐宸学校id");
            // 检查超星学校ID是否重复
            $dxSchool = $this->schoolModel->check_chaoxing_schoolid_exists($xDataId, $schoolId);
            if($dxSchool) throw new Exception("斐宸学校id已存在，录入失败");
            // 请求超星接口
            include_once(APPPATH. "libraries/Feichen.php");
            $feichen = new Feichen();
            $schoolInfo = $feichen->get_school_info($xDataId);

            if(empty($schoolInfo)) {
                throw new Exception('斐宸学校id不存在，请重新输入');
            }
            // echo '<pre>';var_export($schoolInfo);exit;
            // 添加入库数据
            $schoolName = $schoolInfo['departmentName'];
            $data['school_from'] = $schoolFrom;
            $data['school_x_id'] = $xDataId;
        }
        // 自填数据判断
        if(!$schoolName) throw new Exception("请填写学校名称");   
        
        // if(!$provinceCode || !$cityCode || !$areaCode) throw new Exception("请选择完整的学校行政区划");
        // 第三级地区可以为空
        if(!$provinceCode || !$cityCode) throw new Exception("请选择完整的学校行政区划");
        // 入库
        $data['school_name'] = $schoolName;
        $data['school_province'] = $provinceCode;
        $data['school_city'] = $cityCode;
        $data['school_area'] = $areaCode;
        $data['brand_theme'] = $brandTheme;
        $data['school_module_set'] = $this->post("school_module_set");
        $data['school_face_detect'] = $schoolFaceDetect;
        $data['school_face_detect_type'] = $schoolFaceDetectType;
        $data['school_brand_update'] = $schoolBrandUpdate;
        // $data['school_exam_query'] = $schoolExamQuery;
        $data['school_exam'] = $schoolExam;

        // 启用智能门锁
        $data['school_smart_lock'] = $schoolSmartLock;
        $data['is_free_face_sdk'] = $isFreeFaceSdk;
        // 教师考勤
        $data['enable_teacher_sign'] = $enableTeacherSign;
        // $data['school_motto'] = $motto;
        $data['expire_date'] = $expireDate;
        $data['face_similar'] = $faceSimilar;
        $data['notify_expire_time'] = $notifyExpireTime;
        $data['updatetime'] = date("Y-m-d H:i:s");
        if($schoolId) {
            $this->db->update(SchoolModel::$schoolTable, $data,"id='{$schoolId}'");
        } else {
            $data['createtime'] = $data['updatetime'];
            $this->db->insert(SchoolModel::$schoolTable, $data);
            $insertSchoolId = $this->db->insert_id();

            // 银通学校多校区时，不需要新增默认校区
            if($schoolFrom != X_DATA_YINTONG || $this->post('muti_campus') != 1) {
                // 新增一个默认校区
                $campus['school_id'] = $this->db->insert_id();
                $campus['campus_name'] = '默认校区';
                $campus['createtime'] = $campus['updatetime'] = date("Y-m-d H:i:s");
                $this->db->insert(SchoolModel::$campusTable, $campus);
                $insertCampusId = $this->db->insert_id();

                // 默认周一到5开机，5:00-19:00
                $powerTimeV2Json = $this->_get_default_power_time_v2_json();
                $this->configModel->save_school_campus_config($insertSchoolId, $insertCampusId, $this->powerTimeV2Name, $powerTimeV2Json);
            }
        }

        $msg = $schoolId ? '修改学校信息成功' : '添加学校成功';

        // 银通学校保存‘是否分校区’
        if($schoolFrom == X_DATA_YINTONG) {
            $mutiCampus = $this->post('muti_campus');
            $id = $schoolId ? $schoolId : $insertSchoolId;
            $this->configModel->save_school_config($id, $this->mutiCampusName, $mutiCampus);
        }

        exit(json($msg, true));
    }

    // 班牌管理
    public function brand($schoolId){
        $this->schoolInfo = $schoolInfo = $this->schoolModel->get_school_info($schoolId);
        if(!$schoolInfo) show_error("不存在的学校，请返回后重试");
        // 获取班级列表
        $params['schoolId'] = $schoolId;
        $params['isDelete'] = 0;
        $this->classList = $this->classesModel->get_class_list($params);
        // 获取校区列表
        $this->brandCampusList = $this->schoolModel->get_campus_list($params);
        // 获取默认定时开关机
        $brandPawList = array(); 
        foreach($this->brandCampusList as $campus) {
            $schoolBrandPaw = $this->configModel->get_school_campus_config($schoolId, $campus['id'], $this->brandPawName);
            $brandPaw = $schoolBrandPaw['config_value'] ? $schoolBrandPaw['config_value'] : '123456';
            $brandPawList[$campus['id']] = $brandPaw;
        }
        $this->brandPawList = $brandPawList;

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "admin". DIRECTORY_SEPARATOR. "brand");
    }
    // 获取学校班牌列表
    public function get_brand_list($schoolId){
        // 获取数据条数
        $totalParams['schoolId'] = $schoolId;
        $totalParams['getRowNumber'] = true;
        $total = $this->classesModel->get_brand_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $schoolId;
        // 按班级名称排序
        $data['orderByClassName'] = 1;
        $brandList = $this->classesModel->get_brand_list($data);
        foreach($brandList as &$brand) {
            $classInfo = $this->classesModel->get_class_info($brand['class_id']);
            $brand['className'] = $classInfo ? $classInfo['class_name'] : '';
            // 毕业年级
            if($classInfo['is_graduated'] == 1) {
                $brand['className'] = '';
            }
            $campusInfo = $this->schoolModel->get_campus_info($brand['campus_id']);
            $brand['campusName'] = $campusInfo['campus_name'];
            // 班牌类型
            $brand['typeName'] = transform_brand_type($brand['type']);
        }
        // 返回值
        exit(admin_table_data($total, $brandList));
    }
    // 保存表单方法
    public function save_brand_action($schoolId){
        $this->load->model('configModel');
        $brandId = $this->post("id");
        // 不选就默认校区
        $campusParams['schoolId'] = $schoolId;
        $campusParams['isDelete'] = 0;
        $campusList = $this->schoolModel->get_campus_list($campusParams);
        $campusId = $this->post("campus_id") ?  $this->post("campus_id") : $campusList[0]['id'];
        $classId = $this->post("class_id");
        $password = $this->post("brand_password");
        $type = $this->post("type") ? $this->post("type") : 0;
        // 数据检查
        // if(!$campusId) throw new Exception("请选择班牌关联校区");
        if(!$classId) throw new Exception("请选择班牌关联班级");
        if(!$password) throw new Exception("请填写班牌管理密码");
        // 获取默认定时开关机
        $schoolPowerTime = $this->configModel->get_school_campus_config($schoolId, $campusId, $this->powerTimeName);
        $powerTimeJson = $schoolPowerTime['config_value'] ? $schoolPowerTime['config_value'] : '';
        // 入库
        $data['campus_id'] = $campusId;
        $data['class_id'] = $classId;
        $data['brand_password'] = $password;
        $data['brand_camera_zoom'] = BRAND_CAMERA_ZOOM;
        $data['power_time'] = $powerTimeJson;
        $data['type'] = $type;
        $data['updatetime'] = date("Y-m-d H:i:s");
        
        if($brandId) {
             $this->db->update(ClassesModel::$brandTable, $data,"id='{$brandId}'");
        } else {
            $data['school_id'] = $schoolId;
            $data['createtime'] = $data['updatetime'];

            // 默认周一到5开机，5:00-19:00
            $powerTimeV2Json = $this->_get_default_power_time_v2_json();
            $data['power_time_v2'] = $powerTimeV2Json;
            $this->db->insert(ClassesModel::$brandTable, $data);
        }
        $msg = $brandId ? '修改班牌成功' : '添加班牌成功';
        exit(json($msg, true));
    }
    // 批量添加班牌
    public function brand_batch($schoolId){
        $this->schoolInfo = $schoolInfo = $this->schoolModel->get_school_info($schoolId);
        if(!$schoolInfo) show_error("不存在的学校，请返回后重试");
        // 年级班级列表
        $params['schoolId'] = $schoolId;
        $params['getLevelData'] = true;
        // 过滤软删除
        $params['isDelete'] = 0;
        // 只获取行政班
        $params['classType'] = CLASSES_TYPE_NORMAL;
        $this->gradeArray = $this->classesModel->get_grade_class_list($params);

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "admin". DIRECTORY_SEPARATOR. "brand_batch");
    }
    // 批量添加班牌
    public function save_brand_batch_action($schoolId){
        $this->load->model('configModel');
        // 不选就默认校区
        $campusParams['schoolId'] = $schoolId;
        $campusParams['isDelete'] = 0;
        $campusList = $this->schoolModel->get_campus_list($campusParams);
        $campusId = $campusList[0]['id'];
        $brandClass = $this->post("brand_class");
        // 数据检查
        if(!$brandClass) throw new Exception("请选择班级");
        // 获取默认定时开关机
        $schoolPowerTime = $this->configModel->get_school_campus_config($schoolId, $campusId, $this->powerTimeName);
        $powerTimeJson = $schoolPowerTime['config_value'] ? $schoolPowerTime['config_value'] : '';
        // 默认周一到5开机，5:00-19:00
        $powerTimeV2Json = $this->_get_default_power_time_v2_json();
        $classIdArr = explode(',', $brandClass);
        $insertBatch = array();
        foreach($classIdArr as $classId) {
            // 入库
            $data['school_id'] = $schoolId;
            $data['campus_id'] = $campusId;
            $data['class_id'] = $classId;
            $data['brand_password'] = '124578';
            $data['brand_camera_zoom'] = BRAND_CAMERA_ZOOM;
            $data['power_time'] = $powerTimeJson;
            $data['power_time_v2'] = $powerTimeV2Json;
            $data['type'] = 0;
            $data['updatetime'] = date("Y-m-d H:i:s");
            $data['createtime'] = $data['updatetime'];
            array_push($insertBatch, $data);
        }
        $this->db->insert_batch(ClassesModel::$brandTable, $insertBatch);
        $msg = '添加班牌成功';
        exit(json($msg, true));
    }
    // 校区管理
    public function campus($schoolId){
        $this->schoolInfo = $schoolInfo = $this->schoolModel->get_school_info($schoolId);
        if(!$schoolInfo) show_error("不存在的学校，请返回后重试");

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "admin". DIRECTORY_SEPARATOR. "campus");
    }
    public function get_campus_list($schoolId){
        // 获取数据条数
        $totalParams['schoolId'] = $schoolId;
        $totalParams['isDelete'] = 0;
        $totalParams['getRowNumber'] = true;
        $total = $this->schoolModel->get_campus_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['isDelete'] = 0;
        $data['schoolId'] = $schoolId;
        $campusList = $this->schoolModel->get_campus_list($data);
        // 返回值
        exit(admin_table_data($total, $campusList));
    }
    // 保存表单方法
    public function save_campus_action($schoolId){
        $campusId = $this->post("id");
        $campusName = $this->post("campus_name");
        // 数据检查
        if(!$campusName) throw new Exception("请填写校区名称");
        // 入库
        $data['campus_name'] = $campusName;
        $data['updatetime'] = date("Y-m-d H:i:s");
        if($campusId) {
             $this->db->update(SchoolModel::$campusTable, $data,"id='{$campusId}'");
        } else {
            $data['school_id'] = $schoolId;
            $data['createtime'] = $data['updatetime'];
            $this->db->insert(SchoolModel::$campusTable, $data);

            $insertCampusId = $this->db->insert_id();
            // 默认周一到5开机，5:00-19:00
            $powerTimeV2Json = $this->_get_default_power_time_v2_json();
            $this->configModel->save_school_campus_config($schoolId, $insertCampusId, $this->powerTimeV2Name, $powerTimeV2Json);
        }
        $msg = $campusId ? '修改校区信息成功' : '添加校区成功';
        exit(json($msg, true));
    }
    // 删除校区方法
    public function delete_campus_action(){
        $campusId = $this->get("id");
        // 删除校区
        $save['is_delete'] = 1;
        $save['updatetime'] = date('Y-m-d H:i:s');
        $this->db->update(SchoolModel::$campusTable, $save, "id='{$campusId}'");

        // 删除年级
        $this->db->update(ClassesModel::$gradeTable, $save, "campus_id='{$campusId}'");

        // 删除年级
        $this->db->update(ClassesModel::$classTable, $save, "campus_id='{$campusId}'");

        // 删除课室
        $this->db->update(ClassesModel::$classroomTable, $save, "campus_id='{$campusId}'");
        
        // 删除学生
        $this->db->update(SchoolModel::$schoolStudentTable, $save, "campus_id='{$campusId}'");

        $this->load->model('staffModel');
        // 删除执教关系
        $this->db->update(StaffModel::$coachTable, $save, "campus_id='{$campusId}'");

        exit(json("删除校区成功", true));
    }

    // 收费项管理
    public function charge($schoolId){
        $this->schoolInfo = $schoolInfo = $this->schoolModel->get_school_info($schoolId);
        if(!$schoolInfo) show_error("不存在的学校，请返回后重试");

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "admin". DIRECTORY_SEPARATOR. "charge");
    }
    public function get_charge_list($schoolId){
        // 获取数据条数
        $totalParams['schoolId'] = $schoolId;
        $totalParams['isDelete'] = 0;
        $totalParams['getRowNumber'] = true;
        $total = $this->schoolModel->get_charge_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['isDelete'] = 0;
        $data['schoolId'] = $schoolId;
        $chargeList = $this->schoolModel->get_charge_list($data);
        foreach($chargeList as &$charge) {
            if($charge['effect_mode'] == CHARGE_EFFECT_TYPE_LONG) {
                $charge['effect'] = '长期有效';
            } else {
                $charge['effect'] = $charge['effect_time_begin'] . ' 至 ' . $charge['effect_time_end'];
            }
            if($charge['active_mode'] == CHARGE_ACTIVE_TYPE_MONTH) {
                $charge['active'] = $charge['active_month'] . '个月';
            } else {
                $charge['active'] = $charge['active_time'] . '到期';
            }
        }
        // 返回值
        exit(admin_table_data($total, $chargeList));
    }
    // 保存表单方法
    public function save_charge_action($schoolId){
        $chargeId = $this->post("id");
        $name = $this->post("name");
        $price = $this->post("price");
        $effectMode = $this->post("effect_mode") ? $this->post("effect_mode") : '';
        $effectTimeBegin = $this->post("effect_time_begin") ? $this->post("effect_time_begin") : '';
        $effectTimeEnd = $this->post("effect_time_end") ? $this->post("effect_time_end") : '';
        $activeMode = $this->post("active_mode") ? $this->post("active_mode") : '';
        $activeTime = $this->post("active_time") ? $this->post("active_time") : '';
        $activeMonth = $this->post("active_month") ? $this->post("active_month") : '';
        if($price <= 0) {
            throw new Exception("收费价格必须大于0");
        }
        if($effectMode == 1) {
            $effectTime = '';
        } else {
            if(empty($effectTimeBegin) || empty($effectTimeEnd)) {
                throw new Exception("请选择收费有效时间");
            }
            if($effectTimeBegin >= $effectTimeEnd) {
                throw new Exception("开始日期必须小于结束日期");
            }
        }
        if($activeMode == 1) {
            if(empty($activeMonth)) {
                throw new Exception("请填写激活月份");
            }
            if($activeMonth < 1) {
                throw new Exception("激活月份不能小于1");
            }
            $activeTime = '';
        } else {
            if(empty($activeTime)) {
                throw new Exception("请选择激活截止时间");
            }
            $activeMonth = '';
        }
        // 数据检查
        if(!$name) throw new Exception("请填写收费项名称");
        // 入库
        $data['name'] = $name;
        $data['price'] = $price;
        $data['effect_mode'] = $effectMode;
        $data['effect_time_begin'] = $effectTimeBegin;
        $data['effect_time_end'] = $effectTimeEnd;
        $data['active_mode'] = $activeMode;
        $data['active_time'] = $activeTime;
        $data['active_month'] = $activeMonth;
        $data['updatetime'] = date('Y-m-d H:i:s');
        if($chargeId) {
            $this->db->update(SchoolModel::$chargeTable, $data,"id='{$chargeId}'");
        } else {
            $data['school_id'] = $schoolId;
            $data['createtime'] = $data['updatetime'];
            $this->db->insert(SchoolModel::$chargeTable, $data);
        }
        $msg = $chargeId ? '修改收费项信息成功' : '添加收费项成功';
        exit(json($msg, true));
    }
    // 删除收费项方法
    public function delete_charge_action(){
        $chargeId = $this->get("id");
        // 删除用户
        $save['is_delete'] = 1;
        $this->db->update(SchoolModel::$chargeTable, $save, "id='{$chargeId}'");
        exit(json("删除收费项成功", true));
    }

    //获取首页统计数据
    private function _get_index_data(){
        $params['getRowNumber'] = true;
        $params['isDelete'] = 0;
        // 获取教师人数
        $data['teacherNum'] = $this->schoolModel->get_teacher_list($params);
        // 获取学生人数
        $data['studentNum'] = $this->schoolModel->get_student_list($params);
        // 获取课室数量
        $data['classroomNum'] = $this->classesModel->get_classroom_list($params);
        //获取在线班牌数量
        $data['brandOnlineNum'] = $this->classesModel->get_brand_list(array_merge(['online' => 1], $params));
        //获取离线线班牌数量
        $data['brandOfflineNum'] = $this->classesModel->get_brand_list(array_merge(['online' => 0], $params));
        //获取当日人数统计
        $data['dateStudentNum'] = $this->_get_date_student_num(array_merge(['date' => date('Y-m-d')], $params));
        //获取7天的作业量统计  
        $data['dataNum'] = $this->_get_work_data_num($params);
        return $data;
    }

    //获取当日人数统计
    public function get_admin_date_student_num($date){
        $params['getRowNumber'] = true;
        $params['isDelete'] = 0;
        $params = array_merge($params, array('date' => $date));
        $data = $this->_get_date_student_num($params);
        exit(json("", true, $data));
    }

    //获取7天的作业量统计
    public function get_admin_work_data_num($beginDate, $endDate) {
        $params['getRowNumber'] = true;
        $params['isDelete'] = 0;
        $params = array_merge($params, array('range_date' => array($beginDate, $endDate)));
        $data = $this->_get_work_data_num($params);
        exit(json("", true, $data));
    }

    //私有方法，获取当日人数统计
    private function _get_date_student_num($params=array()){
        $data= array();
        //获取所有人数
        $data['studentNum'] = $this->schoolModel->get_student_list($params);
        //获取今天已到人数
        $data['dateSignNum'] = $this->dataModel->get_date_sign_count($params);
        //获取今天未到人数
        $data['dateNotSignNum'] = $data['studentNum'] - $data['dateSignNum'];
        if ($data['dateNotSignNum'] < 0) {
            $data['dateNotSignNum'] = 0;
        }
        //获取今天考勤人数,暂时为0
        $data['dateAttendNum'] = 0;
        //获取今天请假人数,暂时为0
        $data['dateLeaveNum'] = 0;
        return $data;
    }

    //私有方法，获取某段时间内的作业量统计
    private function _get_work_data_num($params=array()){
        $data= array();
        //获取某段时间内作业量
        $data['homeworkNum'] = $this->dataModel->get_homework_count($params);
        //获取某段时间内动态量
        $data['newsNum'] = $this->dataModel->get_news_count($params);
        //获取某段时间内通知量
        $data['notifyNum'] = $this->dataModel->get_notify_count($params);
        //获取某段时间内紧急公告量
        $data['urgentNotifyNum'] = $this->dataModel->get_urgent_notify_count($params);
        //获取某段时间内校园量
        $data['announceNum'] = $this->dataModel->get_announce_count($params);
        return $data;
    }

    // 资源类型管理页面
    public function source_type() {
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "admin". DIRECTORY_SEPARATOR. "source_type");
    }

    // 获取资源类型列表
    public function get_source_type_list() {
        $params['isDelete'] = 0;
        $sourceTypeList = $this->sourceModel->get_source_type_list($params);
        $totalParams['getRowNumber'] = true;
        $totalParams['isDelete'] = 0;
        $total = $this->sourceModel->get_source_type_list($totalParams);
        exit(admin_table_data($total, $sourceTypeList));
    }

    // 保存资源类型
    public function save_source_type_action() {
        $id = $this->post('id');
        $title = $this->post('title');
        if(empty($title)){
            throw new Exception('标题不能为空');
        }
        if(empty($id)){
            $this->db->insert(SourceModel::$schoolSourceTypeTable, array(
                'title' => $title,
                'createtime' => date('Y-m-d H:i:s'),
                'updatetime' => date('Y-m-d H:i:s')   
            ));
        } else {
            $this->db->where('id', $id);
            $this->db->update(SourceModel::$schoolSourceTypeTable, array(
                'title' => $title,
                'updatetime' => date('Y-m-d H:i:s')   
            ));
        }

        $msg = empty($id) ? '保存成功' : '修改成功';
        exit(json($msg, true));
    }

    // 删除资源类型
    public function delete_source_type_action() {
        $id = $this->post('id');
        $this->db->where('id', $id);
        $this->db->update(SourceModel::$schoolSourceTypeTable, array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        ));
        exit(json('删除成功', true));
    }

    // 资源科目管理页面
    public function source_subject() {
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "admin". DIRECTORY_SEPARATOR. "source_subject");
    }

    // 获取资源科目列表
    public function get_source_subject_list() {
        $params['isDelete'] = 0;
        $sourceSubjectList = $this->sourceModel->get_source_subject_list($params);
        $totalParams['getRowNumber'] = true;
        $totalParams['isDelete'] = 0;
        $total = $this->sourceModel->get_source_subject_list($totalParams);
        exit(admin_table_data($total, $sourceSubjectList));
    }

    // 保存资源科目
    public function save_source_subject_action() {
        $id = $this->post('id');
        $title = $this->post('title');
        if(empty($title)){
            throw new Exception('标题不能为空');
        }
        if(empty($id)){
            $this->db->insert(SourceModel::$schoolSourceSubjectTable, array(
                'title' => $title,
                'createtime' => date('Y-m-d H:i:s'),
                'updatetime' => date('Y-m-d H:i:s')   
            ));
        } else {
            $this->db->where('id', $id);
            $this->db->update(SourceModel::$schoolSourceSubjectTable, array(
                'title' => $title,
                'updatetime' => date('Y-m-d H:i:s')   
            ));
        }

        $msg = empty($id) ? '保存成功' : '修改成功';
        exit(json($msg, true));
    }

    // 删除资源出版社
    public function delete_source_subject_action() {
        $id = $this->post('id');
        $this->db->where('id', $id);
        $this->db->update(SourceModel::$schoolSourceSubjectTable, array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        ));
        exit(json('删除成功', true));
    }

    // 资源出版社管理页面
    public function source_publisher() {
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "admin". DIRECTORY_SEPARATOR. "source_publisher");
    }

    // 获取资源出版社列表
    public function get_source_publisher_list() {
        $params['isDelete'] = 0;
        $sourcePublisherList = $this->sourceModel->get_source_publisher_list($params);
        $totalParams['getRowNumber'] = true;
        $totalParams['isDelete'] = 0;
        $total = $this->sourceModel->get_source_publisher_list($totalParams);
        exit(admin_table_data($total, $sourcePublisherList));
    }

    // 保存资源出版社
    public function save_source_publisher_action() {
        $id = $this->post('id');
        $title = $this->post('title');
        if(empty($title)){
            throw new Exception('标题不能为空');
        }
        if(empty($id)){
            $this->db->insert(SourceModel::$schoolSourcePublisherTable, array(
                'title' => $title,
                'createtime' => date('Y-m-d H:i:s'),
                'updatetime' => date('Y-m-d H:i:s')   
            ));
        } else {
            $this->db->where('id', $id);
            $this->db->update(SourceModel::$schoolSourcePublisherTable, array(
                'title' => $title,
                'updatetime' => date('Y-m-d H:i:s')   
            ));
        }

        $msg = empty($id) ? '保存成功' : '修改成功';
        exit(json($msg, true));
    }

    // 删除资源科目
    public function delete_source_publisher_action() {
        $id = $this->post('id');
        $this->db->where('id', $id);
        $this->db->update(SourceModel::$schoolSourcePublisherTable, array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        ));
        exit(json('删除成功', true));
    }

    // 资源年级管理页面
    public function source_grade() {
        // 全部资源年级
        $params['isDelete'] = 0;
        $gradeList = $this->sourceModel->get_source_grade_list($params);
        // var_export($gradeList);
        // 资源年级预定义
        $gradeArr = array();
        foreach($gradeList as $grade) {
            $gradeId = $grade['id'];
            $gradePid = $grade['grade_pid'];

            // 初始化数据
            $gradeEditAction = '<a href="javascript:;" class="grade-edit green"><i class="fa fa-pencil bigger-120"></i> 修改</a>';
            $gradeDeleteAction = '<a href="javascript:;" class="grade-delete red"><i class="fa fa-trash-o bigger-120"></i> 删除</a>';
            $gradeAddSubAction = $gradePid == 0 ? '<a href="javascript:;" class="grade-add-sub blue"><i class="fa fa-plus bigger-120"></i> 添加子年级</a>' : '';
            $gradeTitle = '<span>'. $grade['title'] .'</span>';
            $tree['text'] = $gradeTitle. $gradeDeleteAction. $gradeEditAction. $gradeAddSubAction;
            $tree['type'] = $gradePid ? 'item' : 'folder';
            $tree['attr'] = array("id" => $gradeId);

            // 父级菜单
            if($gradePid == 0) {
                $grade['additionalParameters']['children'] = array();
                 $gradeArr["label_". $gradeId] = $tree;
            } else {
                // 子菜单
                 $gradeArr["label_". $gradePid]['additionalParameters']['children'][] = $tree;
            }
        }
        // 菜单
        $this->gradeStr = json_encode($gradeArr);
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "admin". DIRECTORY_SEPARATOR. "source_grade");
    }

    // 保存资源年级
    public function save_source_grade_action() {
        $id = $this->post('id');
        $pid = $this->post('pid');
        $title = $this->post('title');
        $sort = $this->post('grade_sort');
        if(empty($id)){
            $this->db->insert(SourceModel::$schoolSourceGradeTable, array(
                'title' => $title,
                'grade_pid' => $pid,
                'grade_sort' => $sort,
                'is_delete' => 0,
                'createtime' => date('Y-m-d H:i:s'),
                'updatetime' => date('Y-m-d H:i:s')    
            ));
        } else {
            $this->db->where('id', $id);
            $this->db->update(SourceModel::$schoolSourceGradeTable, array(
                'title' => $title,
                'grade_sort' => $sort,
                'updatetime' => date('Y-m-d H:i:s')
            ));
        }
        $msg = empty($id) ? '添加成功' : '修改成功';
        exit(json($msg, true));
    }

    // 获取资源年级详情
    public function get_source_grade_info() {
        $id = $this->get('id');
        $grade = $this->sourceModel->get_source_grade_info($id);

        exit(json("", true, $grade));
    }

    // 删除资源年级详情
    public function delete_source_grade_action() {
        $id = $this->post('id');
        // 如果是父接口，就一连删除他的子节点
        $grade = $this->sourceModel->get_source_grade_info($id);
        if(empty($grade['grade_pid'])){
            $idArr = array(
                array(
                    'id' => $id,
                    'is_delete' => 1
                ));
            $children = $this->sourceModel->get_source_grade_children($id);
            foreach($children as $child){
                array_push($idArr, array(
                    'id' => $child['id'],
                    'is_delete' => 1
                ));
            }
            $this->db->update_batch(SourceModel::$schoolSourceGradeTable, $idArr, 'id');
        } else {
            $this->db->where('id', $id);
            $this->db->update(SourceModel::$schoolSourceGradeTable, array(
                'is_delete' => 1,
                'updatetime' => date('Y-m-d H:i:s')
            ));
        }
        exit(json('删除成功', true));
    }

    // 插入同步日志
	public function save_sync_log_action() {
        $schoolId = $this->post('school_id');
        $params['schoolId'] = $schoolId;
        $params['isDelete'] = 0;
        $campusList = $this->schoolModel->get_campus_list($params);
        $campusInfo = $campusList[0];
        // 插入日志
        $this->load->library('logger');
        $actionType = $this->logger->get_action_type('sync');
        if($actionType == false) {
            throw new Exception('日志错误');
        }
        $dataArr = array(
            'school_id' => $schoolId,
            'campus_id' => $campusInfo['id'],
            'user_type' => $this->rmxUser['user_type'],
            'user_id' => $this->rmxUser['id'],
            'realname' => $this->rmxUser['username'],
            'action_type' => $actionType,
            'content' => '同步数据'
        );
        $this->logger->save_log_action($dataArr);
       
        exit(json('', true));
    }
}